<script setup lang="ts">
  import { ref, watch } from 'vue'
  import useTimeoutTipService from './service'
  import { empPageSelecct } from '@/api/organize'
  import { Emp } from './types'
  import { ElMessage, FormInstance } from 'element-plus'
  import HButton from '@/components/common/button/HButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import useFormValidateService from '@/services/common/formValidate/useFormValidate'

  const props = defineProps({
    visible: {
      type: Boolean,
      default: () => false,
    },
    orderIds: {
      type: Array<string>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'close'): void
  }>()

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, resetFormValidateResult, formValidateResult } =
    useFormValidateService(['remindEmpType'])

  // 使用超时提醒服务
  const { form, workTimeoutRemindFn, workTimeoutRemindLoading } = useTimeoutTipService(
    props.orderIds,
  )

  // 指定人员下拉选项
  const empOptional = ref<Array<Emp>>([])

  // 获取指定人员下拉选项加载
  const getEmpOptionalLoading = ref(false)

  // 获取指定人员下拉选项
  const getEmpOptional = async () => {
    getEmpOptionalLoading.value = true
    const res = await empPageSelecct({ limit: 0, name: '', page: 0 })
    getEmpOptionalLoading.value = false
    empOptional.value = res.data.data.rows
  }

  // 提醒人员选择事件
  const handleChangeRemindEmpType = (val: Array<number>) => {
    rule.value.remindEmpIds[0].required = false
    if (val.includes(4)) {
      getEmpOptional()
      rule.value.remindEmpIds[0].required = true
    } else {
      form.value.remindEmpIds = []
    }
  }

  const formRef = ref<FormInstance | null>(null)

  // 确定事件
  const onConfirm = () => {
    if (formRef.value) {
      formRef.value.validate(async (valid) => {
        if (valid) {
          if (form.value.remindEmpType.length <= 0) {
            ElMessage({
              type: 'error',
              message: '请选择提醒人员',
            })
            return
          }

          if (form.value.remindEmpType.includes(4) && form.value.remindEmpIds.length <= 0) {
            ElMessage({
              type: 'error',
              message: '请选择指定人员',
            })
            return
          }
          const res = await workTimeoutRemindFn()
          ElMessage({
            type: res.success ? 'success' : 'error',
            message: res.message,
          })
          if (res.success) {
            emits('close')
          }
        }
      })
    }
  }

  /**
   * 弹窗关闭事件
   */
  const onClose = () => {
    if (!workTimeoutRemindLoading.value) {
      emits('close')
      form.value.remindEmpIds = []
      form.value.remindEmpType = [1]
      resetFormValidateResult()
    }
  }

  const rule = ref({
    remindEmpType: [{ required: true, message: '请选择提醒人员', trigger: ['blur', 'change'] }],
    remindEmpIds: [{ required: false, message: '请选择指定人员', trigger: ['blur', 'change'] }],
  })

  watch(
    () => props.orderIds,
    (value) => {
      form.value.workIds = value
    },
    { immediate: true, deep: true },
  )
</script>

<template>
  <div>
    <HModal @close="onClose" :model-value="props.visible" title="超时提醒" size="small">
      <el-form
        ref="formRef"
        label-width="70"
        :model="form"
        :rules="rule"
        v-loading="workTimeoutRemindLoading"
        @validate="handleFormValidate"
        class="modal_form_content"
      >
        <!-- 提醒人员 -->
        <el-form-item
          label="提醒人员"
          prop="remindEmpType"
          class="form_select_item"
          :class="{ error_form_item: !formValidateResult['remindEmpType'] }"
        >
          <el-select
            multiple
            v-model="form.remindEmpType"
            @change="handleChangeRemindEmpType"
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="1"
          >
            <el-option label="工单客服" :value="1" />
            <el-option label="服务商负责人" :value="2" />
            <el-option label="工程师" :value="3" />
            <el-option label="指定人员" :value="4" />
          </el-select>
        </el-form-item>

        <!-- 指定人员 -->
        <el-form-item label="指定人员" class="form_select_item" prop="remindEmpIds">
          <el-select
            multiple
            v-model="form.remindEmpIds"
            :disabled="
              getEmpOptionalLoading || empOptional.length <= 0 || !form.remindEmpType.includes(4)
            "
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="2"
          >
            <el-option v-for="emp in empOptional" :key="emp.id" :value="emp.id" :label="emp.name" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton is-modal type="primary" @click="onConfirm" :disabled="workTimeoutRemindLoading"
          >确定</HButton
        >
        <HButton is-modal @click="onClose" :loading="workTimeoutRemindLoading">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<style scoped lang="scss">
  @import './TimeoutTip.scss';
</style>
